<template>
  <van-field
    type="number"
    v-model="val"
    v-bind="$attrs"
    v-on="$listeners"
    @input="input"
    @blur="blur"
  >
    <template slot="label" v-if="$slots.label">
      <slot name="label"></slot>
    </template>
    <template slot="input" v-if="$slots.input">
      <slot name="input"></slot>
    </template>
    <template slot="leftIcon" v-if="$slots.leftIcon">
      <slot name="leftIcon"></slot>
    </template>
    <template slot="rightIcon" v-if="$slots.rightIcon">
      <slot name="rightIcon"></slot>
    </template>
    <template slot="button" v-if="$slots.button">
      <slot name="button"></slot>
    </template>
    <template slot="extra" v-if="$slots.extra">
      <slot name="extra"></slot>
    </template>
  </van-field>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    fixed: {
      type: [String, Number],
      default: 2
    }
  },
  data() {
    return {
      val: this.value+'',
      inputReg:new RegExp(`\\d+(\\.\\d{1,${this.fixed}}|\\.)?`,'g'),
      blurReg:new RegExp(`\\d+(\\.\\d{1,${this.fixed}})?`,'g'),
    }
  },
  watch: {
    value(v) {
      this.format(this.inputReg, v+'')
    }
  },
  methods: {
    format(reg, v = this.val) {
      const res = (v||'').match(reg);
      v = res ? res[0] : v;
      this.val = v;
    },
    input(v) {
      this.format(this.inputReg, v)
      this.$nextTick(() => {
        this.$emit('input', this.val)
      })
    },
    blur() {
      this.format(this.blurReg)
      this.$nextTick(() => {
        this.$emit('input', this.val)
        this.$emit('blur', this.val)
      })
    }
  }

}
</script>

<style lang="less" scoped>
</style>